package cn.okcmd.myaop.aops;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * create by caoqg on 2021/7/27
 * 功能说明:
 */
@Component
@Aspect
@Slf4j
@Order(-100)
public class MyWebAspect {

    @Pointcut("execution(* cn.okcmd.myaop.web.controllers.biz1..*.*(..))")
    public void beforeBiz1(){}

    @Pointcut("execution(* cn.okcmd.myaop.web.controllers.biz2..*.*(..))")
    public void beforeBiz2(){}

    @Pointcut("@annotation(cn.okcmd.myaop.aops.WebFlag)")
    public void aroundFlag(){};

    @Before("beforeBiz1()")
    public void beforeBiz1Action(){
        log.info("开始业务1相关操作");
    }

    @Before("beforeBiz2()")
    public void beforeBiz2Action(){
        log.info("开始业务2相关操作");
    }

    @Around("aroundFlag()")
    public Object aroundFlagAction(ProceedingJoinPoint point) throws Throwable {
        long t1 = System.currentTimeMillis();
        Throwable t = null;
        String clazzName = point.getTarget().getClass().getSimpleName();
        String methodName = point.getSignature().getName();
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        WebFlag webFlag = method.getAnnotation(WebFlag.class);
        log.info("start biz,{}.{} detail:{}", clazzName, methodName,webFlag.value());
        try{
            Object result = point.proceed();
            return result;
        }catch (Exception e){
            t=e;
            throw e;
        }finally {
            long diffMS = System.currentTimeMillis() - t1;
            log.info("end biz,{}.{} detail:{}, useTime:{}", clazzName, methodName, webFlag.value(), diffMS, t);
        }
    }
}
